﻿using Magicodes.ExporterAndImporter.Excel.AspNetCore;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using NP.BPMReportPlatform.AuthorizationProcessesManager.Dtos;
using NP.BPMReportPlatform.Entities.BPM_Process;
using NP.BPMReportPlatform.RecurringJobs;
using NP.BPMReportPlatform.YJJSZHSQ.Dtos;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using Volo.Abp.Application.Dtos;

namespace NP.BPMReportPlatform.AuthorizationProcessesManager
{
    [ApiController]
    [Route("api/FlowManagement")]
    public class AuthorizationProcessesController : BPMReportPlatformController
    {
        private readonly IAuthorizationProcessesAppService _authorizationProcessesApp;
        private readonly IOldBPMSyncUserJob _oldBPMSyncUserJob;

        public AuthorizationProcessesController(IAuthorizationProcessesAppService authorizationProcessesApp,
            IOldBPMSyncUserJob oldBPMSyncUserJob)
        {
            _authorizationProcessesApp = authorizationProcessesApp;
            _oldBPMSyncUserJob = oldBPMSyncUserJob;
        }

        /// <summary>
        /// 获取用户单个流程权限
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("GetSingleProcessPermission")]
        public async Task<bool> GetSingleProcessPermission([FromBody] GetUserAuthorizationProcessesInput input)
        {
            return await _authorizationProcessesApp.GetSingleProcessPermission(input);
        }


        /// <summary>
        /// 获取用户流程权限
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("GetUserAuthorizationProcesses")]
        public async Task<List<string>> GetUserAuthorizationProcesses([FromBody] string EmployeeCode)
        {
            return await _authorizationProcessesApp.GetUserAuthorizationProcesses(EmployeeCode);
        }

        /// <summary>
        /// 获取微信用户
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("GetWechatUser")]
        public async Task<GetWechatUserOutput> GetWechatUser([FromBody] GetWechatUserInput input)
        {
            return await _authorizationProcessesApp.GetWechatUser(input);
        }

        #region 流程权限
        /// <summary>
        /// 获取流程信息
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [Authorize]
        [HttpGet]
        [Route("GetProcessList")]
        public async Task<PagedResultDto<ProcessInfoOutput>> GetProcessList([FromQuery] ProcessInfoInput input)
        {
            return await _authorizationProcessesApp.GetProcessList(input);
        }
        /// <summary>
        /// 导出流程信息
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [Authorize]
        [HttpPost]
        [Route("ExportProcessList")]
        public async Task<XlsxFileResult<ProcessInfoOutput>> ExportProcessList([FromBody] ProcessInfoInput input)
        {
            var rst = await _authorizationProcessesApp.ExportProcessList(input);
            return new XlsxFileResult<ProcessInfoOutput>(rst, "导出Excel");
        }
        /// <summary>
        /// 编辑流程
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [Authorize]
        [HttpPost]
        [Route("EditProcess")]
        public async Task EditProcessAsync([FromBody] EditProcessInput input)
        {
            await _authorizationProcessesApp.EditProcessAsync(input);
        }

        /// <summary>
        /// 查询流程发起权限配置
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [Authorize]
        [HttpPost]
        [Route("Authorization/GetAuthorizationProcessList")]
        public async Task<PagedResultDto<AuthorizationProcessesSettingsDto>> GetAuthorizationProcessAsync([FromBody] GetAuthorizationProcessesSettingsInput input)
        {
            return await _authorizationProcessesApp.GetAuthorizationProcessAsync(input);
        }

        /// <summary>
        /// 新增流程发起权限配置
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [Authorize]
        [HttpPost]
        [Route("Authorization/AddAuthorizationProcess")]
        public async Task AddAuthorizationProcessAsync([FromBody] AuthorizationProcessesSettings input)
        {
            var newData = new AuthorizationProcessesSettings()
            {
                Id = Guid.NewGuid().ToString(),
                ProcessCode = input.ProcessCode,
                PermissionCode = input.PermissionCode,
                PermissionName = input.PermissionName,
                Type = input.Type,
                PlatformType = input.PlatformType,
            };
            await _authorizationProcessesApp.AddAuthorizationProcessAsync(newData);
        }

        /// <summary>
        /// 编辑
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [Authorize]
        [HttpPost]
        [Route("Authorization/EditAuthorizationProcess")]
        public async Task EditAsync([FromBody] AuthorizationProcessesSettings input)
        {
            if (!input.Id.IsNullOrWhiteSpace())
            {
                await _authorizationProcessesApp.EditAuthorizationProcessAsync(input);
            }
        }

        /// <summary>
        /// 删除审批配置
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [Authorize]
        [HttpDelete]
        [Route("Authorization/DeleteAuthorizationProcess")]
        public async Task DeleteAsync([FromQuery] Guid id)
        {
            await _authorizationProcessesApp.DeleteAuthorizationProcessAsync(id);
        }

        /// <summary>
        /// 验证是否维护了负责人信息
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [Authorize]
        [HttpGet]
        [Route("Authorization/CheckResponsible")]
        public async Task<bool> CheckResponsibleAsync([FromQuery] Guid id)
        {
            return await _authorizationProcessesApp.CheckResponsible(id);
        }

        /// <summary>
        /// 老BPM根据用户工号获取授权流程ID列表
        /// </summary>
        /// <param name="workNumber"></param>
        /// <returns></returns>
        [HttpGet]
        [Route("Authorization/GetUserAuthProcessId")]
        public async Task<List<GetUserProcessAuthForOldBPMOutput>> GetUserAuthProcessId([FromQuery] string workNumber)
        {
            return await _authorizationProcessesApp.GetUserAuthProcessId(workNumber);
        }

        #endregion


        #region 三方登录


        [Route("/api/authorization/thirdpartylogin")]
        [HttpGet]
        public IActionResult Thirdpartylogin(string systemUrl, string employeeCode, string clientId, string clientSecret)
        {
            clientId = clientId ?? "test";
            clientSecret = clientSecret ?? "E5Xd4yMqjP5kjWFKrYgySBju6JVfCzMyFp7n2QmMrME=";

            var certificationUrl = $"{systemUrl}/extension/thirdpartylogin";

            var timestamp = Convert.ToInt64((DateTime.Now - new DateTime(1970, 1, 1, 0, 0, 0, 0)).TotalSeconds); // 时间戳 默认超时5分钟

            var noncestr = Guid.NewGuid().ToString(); // 随机数

            // 拼接字符串 需要Key排序 
            var dictionary = new Dictionary<string, string>()
            {
                {"employeeCode",employeeCode}, // 需要登录的员工号
                {"clientId",clientId}, // 财务管理平台提供的Client
                {"redirectUrl",WebUtility.UrlEncode(systemUrl)}, //需要登陆后重定向的url 这里需要UrlEncode
                {"timestamp",timestamp.ToString()},
                {"noncestr",noncestr}
            };

            var nosignature = new StringBuilder();
            foreach (var keyValuePair in dictionary.OrderBy(p => p.Key)) // key排序 正序 拼接后 如下面的例子
            {
                nosignature.AppendFormat("{0}={1}&", keyValuePair.Key, keyValuePair.Value);
            }

            nosignature = nosignature.Remove(nosignature.Length - 1, 1);
            // clientId=test&employeeCode=00027063&noncestr=67b5f93c-3f7c-43c4-8eb3-08bdaec24fcc&redirectUrl=http%3A%2F%2Ffinancetest.nipponpaint.com.cn%2Fservicecharges%2Fwithhold_list&timestamp=1595955904

            // 将得到的signature 放入url中

            var signature = GetSignature(nosignature.ToString(), clientSecret);

            dictionary.Add("signature", signature);

            var query = new StringBuilder("?");
            foreach (var keyValuePair in dictionary)
            {
                query.AppendFormat("{0}={1}&", keyValuePair.Key, keyValuePair.Value);
            }

            query = query.Remove(query.Length - 1, 1);
            // ?employeeCode=00027063&clientId=test&redirectUrl=http%3A%2F%2Ffinancetest.nipponpaint.com.cn%2Fservicecharges%2Fwithhold_list&timestamp=1595955904&noncestr=67b5f93c-3f7c-43c4-8eb3-08bdaec24fcc&signature=91e1d6d3ddd68d792549eda40406048bb7f04fa2

            var redirectUrl = certificationUrl + query.ToString();
            return Redirect(redirectUrl);
        }

        private string GetSignature(string rawData, string sessionKey)
        {
            return GetSha1(rawData + sessionKey);
        }

        private string GetSha1(string encryptStr)
        {
            var hash = SHA1.Create().ComputeHash(Encoding.UTF8.GetBytes(encryptStr));
            StringBuilder stringBuilder = new StringBuilder();
            foreach (var num in hash)
            {
                stringBuilder.AppendFormat("{0:x2}", num);
            }

            return stringBuilder.ToString();
        }

        #endregion


        /// <summary>
        /// 老BPM人员同步
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [Route("Authorization/OldBPMSyncUser")]
        public async Task OldBPMSyncUser()
        {
            await _oldBPMSyncUserJob.SyncUser();
        }
    }
}
